package com.seckill.exception;

import com.seckill.enums.ResultEnum;
import com.seckill.result.Result;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandle {
    @ExceptionHandler(value = Exception.class)
    public Result<String> catchException(Exception ex, HttpServletRequest request, HttpServletResponse response){
        System.out.println(request);
        System.out.println(response);
        //自定义异常
        if (ex instanceof SeckillException) {
            ex.printStackTrace();
            SeckillException seckillException = (SeckillException) ex;
            return ((SeckillException) ex).getResult();
        }else if (ex instanceof BindException) {//JSR303异常
            BindException bindException = (BindException) ex;
            List<ObjectError> list = bindException.getAllErrors();
            String errorMsg = null;
            if(!CollectionUtils.isEmpty(list)){
                ObjectError objectError = list.get(0);
                errorMsg = objectError.getDefaultMessage();
            }
            return Result.error(ResultEnum.match(errorMsg,ResultEnum.SERVER_ERROR));
        }else{
            //未知异常
            ex.printStackTrace();
            return Result.error(ResultEnum.SERVER_ERROR);
        }
    }
}
